<?php
/*
 * @Author: 李志刚
 * @CopyRight: 2022-2099 李志刚（854378082@qq.com）
 * @Date: 2020-09-20 21:13:41
 * @Description: 用户登录
 * @LastEditors: 李志刚
 * @LastEditTime: 2022-05-06 10:02:27
 * @FilePath: /CoinCMF/app/Http/Controllers/Api/UserController.php
 */

namespace App\Http\Controllers\Api;

use App\Customize\Func;
use App\Models\User\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;

class UserController extends Controller
{
    // 微信code换取session，openid
    public function postWxCode(Request $request)
    {
        try {
            $rules = [
                'code' => 'required|max:255',
            ];
            $attrs = array(
                'code' => '授权code',
            );
            $validator = Validator::make($request->input(), $rules,[], $attrs);
            if ($validator->fails()) {
                return $this->resJson(400, $validator->errors()->all()[0]);
            }
            // 微信认证部分
            $code = $request->input('code');
            $app = app('wechat.mini_program');
            $data = $app->auth->session($code);
            if (!isset($data['openid'])) return $this->resJson(400, '微信授权失败');
            return $this->resJson(200, '成功', $data);
        } catch (\Throwable $th) {
            return $this->resJson(500, '服务器异常，请稍后再试');
        }
    }
    public function postEncrypt(Request $request)
    {
        try {
            $rules = [
                'session' => 'required|max:255',
                'iv' => 'required|max:255',
                'encryptedData' => 'required|max:1255',
            ];
            $attrs = array(
                'session' => '登录信息',
                'iv' => '加密密钥',
                'encryptedData' => '加密数据',
            );
            $validator = Validator::make($request->input(), $rules,[], $attrs);
            if ($validator->fails()) {
                return $this->resJson(400, $validator->errors()->all()[0]);
            }
            $data = $request->all();
            $app = app('wechat.mini_program');
            $decryptedData = $app->encryptor->decryptData($data['session'], $data['iv'], $data['encryptedData']);
            return $this->resJson(200, '成功', $decryptedData);
        } catch (\Throwable $th) {
            return $this->resJson(500, '服务器异常，请稍后再试');
        }
    }
    public function postWxLogin(Request $request)
    {
        try {
            $rules = [
                'phone' => 'required|regex:/^1[3456789]\d{9}$/',
                'openid' => 'required|max:255',
                'nickname' => 'nullable|max:255',
                'thumb' => 'nullable|max:255',
            ];
            $attrs = array(
                'phone' => '手机号',
                'openid' => '微信信息',
                'nickname' => '昵称',
                'thumb' => '头像',
            );
            $validator = Validator::make($request->input(), $rules,[], $attrs);
            if ($validator->fails()) {
                return $this->resJson(400, $validator->errors()->all()[0]);
            }
            $data = $request->all();
            // 查有没有这个用户
            $user = User::where('phone', $data['phone'])->where('del_flag', 0)->first();
            if (is_null($user)) {
                $user = User::create(['phone' => $data['phone'], 'openid' => $data['openid'], 'nickname' => $data['nickname'], 'thumb' => $data['thumb']]);
            } else {
                User::where('id', $user->id)->update(['openid' => $data['openid'], 'nickname' => $data['nickname'], 'thumb' => $data['thumb']]);
            }
            // token
            $token = md5(md5($user->id . '-SMZ-' . $user->phone . '-' . time()));
            // 放到redis里边，先删除旧的，有效期一天
            $oldtoken = cache()->get('u-phone:' . $user->phone);
            cache()->forget('u-token:' . $oldtoken);
            cache()->put('u-phone:' . $user->phone, $token);
            cache()->put('u-token:' . $token, json_encode(['id' => $user->id, 'phone' => $user->phone, 'openid' => $user->openid]), 3600 * 24 * 365);
            $res = ['id' => $user->id, 'phone' => $user->phone, 'openid' => $user->openid, 'token' => $token];
            return $this->resJson(200, '成功', $res);
        } catch (\Throwable $th) {
            return $this->resJson(500, '服务器异常，请稍后再试', $e->getMessage());
        }
    }
    public function postPhoneLogin(Request $request)
    {
        try {
            $rules = [
                'phone' => 'required|regex:/^1[3456789]\d{9}$/',
                'password' => 'required|max:15',
            ];
            $attrs = array(
                'phone' => '手机号',
                'password' => '密码',
            );
            $validator = Validator::make($request->input(), $rules,[], $attrs);
            if ($validator->fails()) {
                return $this->resJson(400, $validator->errors()->all()[0]);
            }
            $data = $request->all();
            // 查有没有这个用户
            $user = User::where('phone', $data['phone'])->where('del_flag', 0)->first();
            if (is_null($user)) {
                $crypt = Func::str_random(10);
                $pwd = Func::makepwd($data['password'], $crypt);
                $user = User::create(['phone' => $data['phone'], 'password' => $pwd, 'crypt' => $crypt]);
            } else {
                $pwd = Func::makepwd($data['password'], $user->crypt);
                if ($pwd != $user->password) {
                    return $this->resJson(400, '密码错误');
                }
            }
            // token
            $token = md5(md5($user->id . '-SMZ-' . $user->phone . '-' . time()));
            // 放到redis里边，先删除旧的，有效期一天
            $oldtoken = cache()->get('u-phone:' . $user->phone);
            cache()->forget('u-token:' . $oldtoken);
            cache()->put('u-phone:' . $user->phone, $token);
            cache()->put('u-token:' . $token, json_encode(['id' => $user->id, 'phone' => $user->phone, 'openid' => $user->openid]), 3600 * 24 * 365);
            $res = ['id' => $user->id, 'phone' => $user->phone, 'openid' => $user->openid, 'token' => $token];
            return $this->resJson(200, '成功', $res);
        } catch (\Throwable $th) {
            return $this->resJson(500, '服务器异常，请稍后再试', $th->getMessage());
        }
    }
    public function postEditInfo(Request $request)
    {
        try {
            $rules = [
                'detail_id' => 'required|integer',
                'nickname' => 'required|max:255',
                'thumb' => 'required|max:255',
            ];
            $attrs = array(
                'detail_id' => '用户ID',
                'nickname' => '昵称',
                'thumb' => '头像',
            );
            $validator = Validator::make($request->input(), $rules,[], $attrs);
            if ($validator->fails()) {
                return $this->resJson(400, $validator->errors()->all()[0]);
            }
            $data = $request->all();
            // 查有没有这个用户
            User::where('id', $data['detail_id'])->update(['nickname' => $data['nickname'], 'thumb' => $data['thumb']]);
            return $this->resJson(200, '成功');
        } catch (\Throwable $th) {
            return $this->resJson(500, '服务器异常，请稍后再试');
        }
    }
    public function postDetail(Request $request)
    {
        try {
            $rules = [
                'detail_id' => 'required|integer',
            ];
            $attrs = array(
                'detail_id' => 'ID',
            );
            $validator = Validator::make($request->input(), $rules, [], $attrs);
            if ($validator->fails()) {
                return $this->resJson(400, $validator->errors()->all()[0]);
            }
            $data = $request->all();
            // 查有没有这个用户
            $detail = User::where('id', $data['detail_id'])->first();
            return $this->resJson(200, '成功', $detail);
        } catch (\Throwable $th) {
            return $this->resJson(500, '服务器异常，请稍后再试');
        }
    }
}
